#ifndef TCP_CONNECTION_H
#define TCP_CONNECTION_H
#include <list>
#include <thread>
#include <mutex>
#include <memory>
#include <sstream>
#include <boost/asio.hpp>
#include "common/logger.h"
#include "callback.h"

using namespace boost::asio;
using namespace boost::asio::ip;

class TcpConnection
	: public std::enable_shared_from_this<TcpConnection>
{
public:
	TcpConnection(io_service& io_server);
	~TcpConnection()
	{
		disconnect();
	}

	void start();

	void disconnect()
	{
		if (socket_.is_open())
			socket_.close();
	}

	tcp::socket& socket()
	{
		return socket_;
	}

	void sendMessage(const std::string& message);

	std::string remoteAddr()
	{
		ostringstream oss;
		oss << remote_addr_ << ":" << remote_port_;
		return oss.str();
	}

private:
	void onMessage(const boost::system::error_code& err, std::size_t bytes_transferred);

	void onWriteFinish(const boost::system::error_code& err, std::size_t bytes_transferred);

private:
	tcp::socket				socket_;
	boost::asio::strand		strand_;

	boost::asio::streambuf	req_stream_;
	boost::asio::streambuf	resp_stream_;

	std::mutex				mutex_;

	std::string				remote_addr_;
	short					remote_port_;
};

typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;

#endif
